<?php
//ini_set('max_execution_time', 900);
set_time_limit(30);
include "./include/om_config.inc";
if(!isset($_SESSION['s_activId']))
{
  $_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
  header("Location:checkLogin.php");
}
else
{	
  $smarty = new SmartyWWW();
  $fromDate = isset($_POST['fromDateYear'])? $_POST['fromDateYear']."-".strtoupper($_POST['fromDateMonth'])."-".$_POST['fromDateDay']:mktime(0, 0, 0, date("m")  , date("d")-1, date("Y"));
  $toDate = isset($_POST['toDateYear'])? $_POST['toDateYear']."-".strtoupper($_POST['toDateMonth'])."-".$_POST['toDateDay']:mktime(0, 0, 0, date("m")  , date("d")-1, date("Y"));
  $smarty->assign("fromDate",$fromDate);
  $smarty->assign("toDate",$toDate);
  
  $scriptExclude = "'ALOKTEXT', 'ABB', 'FTSE100', 'MPHASIS', 'PEL', 'CENTRALBK', 'CNXINFRA', 'CNXIT', 'CNXPSE', 'MINIFTY', 'NCC', 'NFTYMCAP50', 'S&P500', 'SCI' , 'SOUTHBANK',
                    'ABAN', 'AIL', 'BAJAJHIND', 'BAJAJHLDNG', 'BALRAMCHIN', 'BEL', 'BEML', 'BFUTILITIE', 'BGRENERGY', 'BOMDYEING', 'BOSCHLTD', 'COREEDUTEC', 'CUMMINSIND', 
                    'DCB', 'DELTACORP', 'EDUCOMP', 'ESCORTS', 'ESSAROIL', 'FORTIS', 'GESHIP', 'GLAXO', 'GMDCLTD', 'GUJFLUORO', 'HCC', 'HINDOILEXP', 'INDIAINFO', 'INDIANB', 'JETAIRWAYS', 
                    'JINDALSAW', 'JSWISPAT', 'LITL', 'MAX', 'MRPL', 'MTNL', 'NAGAROIL', 'OIL', 'ONMOBILE', 'ORCHIDCHEM', 'PATELENG', 'PIRHEALTH', 'PIRHEALTH', 'POLARIS', 
                    'PRAJIND', 'ROLTA', 'RUCHISOYA', 'SKUMARSYNF', 'SOBHA', 'SREINFRA', 'STRTECH', 'SUZLON', 'TATACOFFEE', 'TTKPRESTIG', 'TTML', 'TVSMOTOR', 'VIDEOIND', 'VIPIND'
                   ";
  
  $displayItemName =0;
  if(isset($_POST['itemId']) && ($_POST['itemId'] == '0' || $_POST['itemId'] == "A-G" || $_POST['itemId'] == "H-M" || $_POST['itemId'] == "N-T" || $_POST['itemId'] == "U-Z"))
  {
  	$displayItemName = '1';
  }
  $smarty->assign("displayItemName",$displayItemName);
  /////For Display in table ////
  
         
	$weekDay               = array();
	$expiryDate            = array();
	$expiryDateBc          = array();
	$itemName              = array();
	$bhavcopyDate          = array();
	$openPrice             = array();
	$highPrice             = array();
	$lowPrice              = array();
	$closePrice            = array();
	$openInterest          = array();
	$openInterestInLots    = array();
	$openInterestDisp      = array();
	$displayCurrentRow     = array();
	$lotSize               = array();
	$openInterestTot       = array();
	$openInterestInLotsTot = array();
	$displayEndedContract  = array();
	$endedOpenInterest     = array();
	$openInterestInLotsTotPending = array();
	$exchangeValue         = array();
  $highCount             = 0;
  $lowCount              =0;
  $highestHighPriceAssoc = array();
  $lowestLowPriceAssoc = array();
  $highestHighPrice      = array();
  $highestHighItem       = array();
  $lowestLowPrice        = array();
  $lowestLowItem         = array();
  
   //selectitem:Start
   $itemQuery = "SELECT itemId,min 
                   FROM item";
   $itemQueryResult = mysql_query($itemQuery);
	 $count=0;
   while($itemQueryRow = mysql_fetch_array($itemQueryResult))
   	 $itemMinArray[$itemQueryRow['itemId']] = $itemQueryRow['min'];
   //selectitem:End

   $selectQuery = "SELECT exchange,contractCode,expiryDate from bhavcopyf_o ORDER BY bhavcopyDate,expiryDate";
   $resultQuery = mysql_query($selectQuery);
	 $count=0;
   while($rowQuery = mysql_fetch_array($resultQuery))
   {
   	 $contract[$count] = $rowQuery['contractCode'];
   	 $expiry[$count] = $rowQuery['expiryDate'];
		 $exchange[$count] = $rowQuery['exchange'];
		 $count++;
	 }
   $sortBy          = isset($_POST['sortBy'])? $_POST['sortBy'] : "Date";
   $currentItemId   = isset($_POST['itemId'])? $_POST['itemId'] :0;
   $expDate         = isset($_POST['expiryDate'])? $_POST['expiryDate'] : $expiry[0]; 
   $currentExchange = isset($_POST['exchange'])? $_POST['exchange'] : $expiry[0]; 
   $displayCount = 0;  
   $displayQuery = "SELECT * FROM bhavcopyf_o WHERE bhavcopyDate >= '".$fromDate."' AND bhavcopyDate <= '".$toDate."'
                       AND contractCode NOT IN (".$scriptExclude.")";
/////////////////
   if($currentItemId == "A-G")
   {
 	  $displayQuery .= " AND (
 	                           contractCode LIKE 'A%'  OR
 	                           contractCode LIKE 'B%' OR
 	                           contractCode LIKE 'C%' OR
 	                           contractCode LIKE 'D%' OR
 	                           contractCode LIKE 'E%' OR
 	                           contractCode LIKE 'F%' OR
 	                           contractCode LIKE 'G%'
 	                         ) ";
   }
   else if($currentItemId == "H-M")
   {
 	  $displayQuery .= " AND (
 	                           contractCode LIKE 'H%' OR
 	                           contractCode LIKE 'I%' OR
 	                           contractCode LIKE 'J%' OR
 	                           contractCode LIKE 'K%' OR
 	                           contractCode LIKE 'L%' OR
 	                           contractCode LIKE 'M%'
 	                         ) ";
   }
   else if($currentItemId == "N-T")
   {
 	   $displayQuery .= " AND (
 	                           contractCode LIKE 'N%' OR
 	                           contractCode LIKE 'O%' OR
 	                           contractCode LIKE 'P%' OR
 	                           contractCode LIKE 'Q%' OR
 	                           contractCode LIKE 'R%' OR
 	                           contractCode LIKE 'S%' OR
 	                           contractCode LIKE 'T%' 
 	                          ) ";
   }
   else if($currentItemId == "U-Z")
   {
 	   $displayQuery .= " AND (
 	                           contractCode LIKE 'U%' OR
 	                           contractCode LIKE 'V%' OR
 	                           contractCode LIKE 'W%' OR
 	                           contractCode LIKE 'X%' OR
 	                           contractCode LIKE 'Y%' OR
 	                           contractCode LIKE 'Z%'
 	                          ) ";
   }
/////////////////

   if($currentItemId != '0' && $currentItemId != 'A-G' && $currentItemId != 'H-M' && $currentItemId != 'N-T' && $currentItemId != 'U-Z')									
   {
   	 $displayQuery .= " AND contractCode='".$currentItemId."' ";
   
	   if($currentExchange !='BSE CASH' && $expDate != 0)
	   { 
	     $displayQuery .= " AND expiryDate='".$expDate."'"; 
	   }
   }
   $displayQuery .="  AND exchange='".$currentExchange."'";
   if($sortBy == "Item Name")
   $displayQuery .="  ORDER BY contractCode,expiryDate,bhavcopyDate";
   else   
   $displayQuery .="  ORDER BY contractCode,bhavcopyDate,expiryDate";      
   $displayResult = mysql_query($displayQuery);
   $currentTotal            = 0;
   $currentTotalInLots      = 0;
   $displayCountCurrentRow  = 0;
   $displayEndedContractVar = 0;
   $endedOpenInterestVar    = 0;
   while($displayRow = mysql_fetch_array($displayResult))
   {  
   		$weekDay[$displayCount] = date("l", mktime(0,0,0,substr($displayRow['bhavcopyDate'],5,2),substr($displayRow['bhavcopyDate'],8,2),substr($displayRow['bhavcopyDate'],0,4)));
   		$bhavcopyDateYYYYMMDD[$displayCount] = $displayRow['bhavcopyDate'];
   		$bhavcopyDate[$displayCount]         = substr($displayRow['bhavcopyDate'],0,4)."_".substr($displayRow['bhavcopyDate'],5,2)."_".substr($displayRow['bhavcopyDate'],8,2);
      $itemName[$displayCount] 		         = $displayRow['contractCode'];
      $expiryDate[$displayCount] 	         = $displayRow['expiryDate'];
      $expiryDateBc[$displayCount]         = $displayRow['expiryDateBc'];
      $openPrice[$displayCount] 	         = $displayRow['openPrice'];
      $highPrice[$displayCount]  	         = $displayRow['highPrice'];
      $lowPrice[$displayCount] 		         = $displayRow['lowPrice'];
      $closePrice[$displayCount]           = $displayRow['closePrice'];
      $openInterest[$displayCount]         = $displayRow['openInterest'];
      $currentItemMin = (isset($itemMinArray[$displayRow['contractCode']]) && $itemMinArray[$displayRow['contractCode']] != 0) ? $itemMinArray[$displayRow['contractCode']] : 1;
      $openInterestInLots[$displayCount]   = $displayRow['openInterest'] / $currentItemMin;
      
      if($displayCount > 0 && $itemName[$displayCount - 1] == $displayRow['contractCode'] 
               && $bhavcopyDateYYYYMMDD[$displayCount - 1] == $displayRow['bhavcopyDate'])
        $displayCurrentRow[$displayCount] = "N";
      else
      {
        $displayCurrentRow[$displayCount] = "Y";
        $displayCountCurrentRow           = $displayCount;
	      
	      //To find the Highest Price and Lowest Price from data : Start
        //if(!isset($highestHighPriceAssoc[$displayRow['contractCode']]))
        if(!array_key_exists($displayRow['contractCode'], $highestHighPriceAssoc))
        {
          $highestHighPriceAssoc[$displayRow['contractCode']] = $displayRow['highPrice'];
          $highestHighPrice[$highCount]                       = $displayRow['highPrice'];
          $highestHighItem[$highCount]                        = $displayRow['contractCode'];
          $highCount++;
        }
        elseif($highestHighPrice[array_search($displayRow['contractCode'], $highestHighItem)] < $displayRow['highPrice'])
	      {
	        $currentItemHighCount = array_search($displayRow['contractCode'], $highestHighItem);
          $highestHighPriceAssoc[$displayRow['contractCode']] = $displayRow['highPrice'];
          $highestHighPrice[$currentItemHighCount]            = $displayRow['highPrice'];
          $highestHighItem[$currentItemHighCount]             = $displayRow['contractCode'];
	      }
	      if(!array_key_exists($displayRow['contractCode'], $lowestLowPriceAssoc))
        {
          $lowestLowPriceAssoc[$displayRow['contractCode']] = $displayRow['lowPrice'];
          $lowestLowPrice[$lowCount]                       = $displayRow['lowPrice'];
          $lowestLowItem[$lowCount]                        = $displayRow['contractCode'];
          $lowCount++;
        }
        elseif($lowestLowPrice[array_search($displayRow['contractCode'], $lowestLowItem)] > $displayRow['lowPrice'])
	      {
	        $currentItemLowCount = array_search($displayRow['contractCode'], $lowestLowItem);
          $lowestLowPriceAssoc[$displayRow['contractCode']] = $displayRow['lowPrice'];
          $lowestLowPrice[$currentItemLowCount]            = $displayRow['lowPrice'];
          $lowestLowItem[$currentItemLowCount]             = $displayRow['contractCode'];
	      }


//	      if($lowestLowPrice > $lowPrice[$displayCount] && $lowPrice[$displayCount] != 0)
//	        $lowestLowPrice = $lowPrice[$displayCount];
	      //To find the Highest Price and Lowest Price from data : End
      }
        
      if($displayCount > 0 && $itemName[$displayCount - 1] == $itemName[$displayCount] 
               && $bhavcopyDateYYYYMMDD[$displayCount - 1] == $displayRow['bhavcopyDate'])
        $openInterestDisp[$displayCount]  			= "Y";
      else
      {
        $currentTotal  = 0;
        $currentTotalInLots  = 0;
        $displayEndedContractVar = 0;
        $endedOpenInterestVar    = 0;
        $openInterestDisp[$displayCount]  			= "N";
      }
      
      $currentTotal  += $displayRow['openInterest'];
      $currentTotalInLots  += $displayRow['openInterest'] / $currentItemMin;
      $lotSize[$displayCountCurrentRow]               = $currentItemMin;
      $openInterestTot[$displayCountCurrentRow]  			= $currentTotal;
      $openInterestInLotsTot[$displayCountCurrentRow]	= $currentTotalInLots;
      
      if($displayRow['bhavcopyDate'] == $displayRow['expiryDate'])
      {
        $displayEndedContractVar = 1;
        $endedOpenInterestVar    = $displayRow['openInterest'] / $currentItemMin;
      }
      $displayEndedContract[$displayCountCurrentRow] = $displayEndedContractVar;
      $endedOpenInterest[$displayCountCurrentRow]    = $endedOpenInterestVar;
      $openInterestInLotsTotPending[$displayCountCurrentRow]    = $openInterestInLotsTot[$displayCountCurrentRow] - $endedOpenInterestVar;
      
      $displayCount++;
   }
  ////Request parameters, if passed : transfer to proper variable :End
  
  //Item records :Start
  $itemIdSelected = $currentItemId;
  $itemIdValues = array();
  $itemIdOptions = array();
  $itemCount = 0;
  $itemIdValues[0]  = '0';
  $itemIdOptions[0] = "All";
  $itemRecords = array();
  $itemCount++;
  $selectedExchange = isset($_POST['exchange'])? $_POST['exchange'] :'F_O';
  $smarty->assign("selectedExchange",$selectedExchange);
  
  if(isset($_POST['fromDateYear']))
    $dateRangeCondition = " AND bhavcopyDate >= '".$fromDate."'
                            AND bhavcopyDate <= '".$toDate."'";
  else
    $dateRangeCondition = "";
  
  $itemQuery = "SELECT DISTINCT(contractCode) FROM bhavcopyf_o 
                 WHERE exchange='".$selectedExchange."' ".$dateRangeCondition." 
                   AND contractCode NOT IN (".$scriptExclude.")
              ORDER BY contractCode";
  $itemResult = mysql_query($itemQuery);
  while($itemRow = mysql_fetch_array($itemResult))
  {
    $itemIdValues[$itemCount]  = $itemRow['contractCode'];
    $itemIdOptions[$itemCount] = $itemRow['contractCode'];
    $itemCount++;
  }
  
  //Expiry records :Start
  if(isset($_POST['expiryDate']))
  {
    if($_POST['itemIdChanged']==1 || $currentItemId=="All")
      $expiryDateSelected = 0;
    else
      $expiryDateSelected = $_POST['expiryDate'];
  }
  else
    $expiryDateSelected = 0;
    
  $expiryDateValues = array();
  $expiryDateOptions = array();
  
  $i=0;
  $expiryDateValues[0]  = 0;
  $expiryDateOptions[0] = 'All';
  $i++;
    
  if($currentItemId!="All")
  {
    $expiryQuery = "SELECT DISTINCT(expiryDate),expiryDateBc FROM bhavcopyf_o 
                    WHERE contractCode='".$currentItemId."' ORDER BY expiryDate";
    $expiryResult = mysql_query($expiryQuery);
    while($expiryRow = mysql_fetch_array($expiryResult))
    {
        $expiryDateValues[$i]  = $expiryRow['expiryDate'];
        $expiryDateOptions[$i] = $expiryRow['expiryDateBc'];
        $i++;
    }
  }
  if(isset($_POST['avgLow']) && isset($_POST['avgHigh']))
  {	
    $avgHigh=$_POST['avgHigh'];
    $avgLow=$_POST['avgLow'];
  }
  
  $selectExchange="SELECT DISTINCT (exchange) FROM bhavcopyf_o";
  $resultExchange = mysql_query($selectExchange);    
  $j=0;
  while($rowExchange = mysql_fetch_array($resultExchange))
  {
  	$exchangeValue[$j] = $rowExchange['exchange'];
  	$j++;
  }
   
  //////End for display in table //////////

	////Sort By Array : Start
	$sortingSelected  = isset($_POST['sortBy']) ? $_POST['sortBy'] : "Date";

//	$sortValuesArr[0] = "Item Name";
//	$sortOutputArr[0] = "Item Name";
	$sortValuesArr[0] = "Date";
	$sortOutputArr[0] = "Date";	
	
	////Sort By Array : End  
  
  $avgHigh = isset($avgHigh)? $avgHigh : "";

  $smarty->assign("sortValuesArr",$sortValuesArr);
  $smarty->assign("sortOutputArr",$sortOutputArr);
  $smarty->assign("sortingSelected",$sortingSelected);
  $smarty->assign("weekDay",$weekDay);
  $smarty->assign("itemName",$itemName);
  $smarty->assign("expiryDate",$expiryDate);
  $smarty->assign("expiryDateBc",$expiryDateBc);
  $smarty->assign("bhavcopyDate",$bhavcopyDate);
  $smarty->assign("openPrice",$openPrice);
  $smarty->assign("highPrice",$highPrice);
  $smarty->assign("lowPrice",$lowPrice);
  $smarty->assign("closePrice",$closePrice);
  $smarty->assign("openInterest",$openInterest);
  $smarty->assign("openInterestInLots",$openInterestInLots);
  $smarty->assign("openInterestDisp",$openInterestDisp);
  $smarty->assign("displayCurrentRow",$displayCurrentRow);
  $smarty->assign("lotSize",$lotSize);
  $smarty->assign("openInterestTot",$openInterestTot);
  $smarty->assign("openInterestInLotsTot",$openInterestInLotsTot);
  $smarty->assign("displayEndedContract",$displayEndedContract);
  $smarty->assign("endedOpenInterest",$endedOpenInterest);
  $smarty->assign("openInterestInLotsTotPending",$openInterestInLotsTotPending);
  
  $smarty->assign("itemIdSelected",$itemIdSelected);
  $smarty->assign("itemIdValues",$itemIdValues);
  $smarty->assign("itemIdOptions",$itemIdOptions);
  $smarty->assign("expiryDateSelected",$expiryDateSelected);
  $smarty->assign("expiryDateValues",$expiryDateValues);
  $smarty->assign("expiryDateOptions",$expiryDateOptions);
  $smarty->assign("exchangeValue",$exchangeValue);
  $smarty->assign("highestHighPrice",$highestHighPrice);
  $smarty->assign("highestHighItem",$highestHighItem);
  $smarty->assign("lowestLowPrice",$lowestLowPrice);
  $smarty->assign("lowestLowItem",$lowestLowItem);
  $smarty->display('bhavcopyListF_O.tpl');
}
?>